package com.yin.myproject.sort;

/**
 * 快速排序算法
 * Created by Eason on 2017/9/12.
 * 时间复杂度 O(nlogn)
 */
public class QuickSort {

    public static void main(String[] args) {
        int arr[] = {1, 2, -3, 4, -5, 6, -7, 9, 8, 2, 4, 6, 11, 23, 45, 21, 34, 78, -20};
        sort(arr, 0, arr.length - 1);
    }

    public static int index(int[] arr, int _left, int _right) {
        int left = _left;
        int right = _right;
        int key = arr[left];
        while (left < right) {
            while (arr[right] >= key && right > left) {
                right--;
            }
            arr[left] = arr[right];
            while (arr[left] <= key && right > left) {
                left++;
            }
            arr[right] = arr[left];
        }
        arr[right] = key;
        return right;
    }

    public static void sort(int[] arr, int left, int right) {
        if (left >= right)
            return;
        int index = index(arr, left, right);
        System.out.println("index is " + index + " ");
        sort(arr, left, index);
        sort(arr, index + 1, right);
    }

    public static void sortDemo(int a[], int low, int hight) {
        int i, j, index;
        if (low > hight) {
            return;
        }
        i = low;
        j = hight;
        index = a[i]; // 用子表的第一个记录做基准
        while (i < j) { // 从表的两端交替向中间扫描
            while (i < j && a[j] >= index)
                j--;
            if (i < j)
                a[i++] = a[j];// 用比基准小的记录替换低位记录
            while (i < j && a[i] < index)
                i++;
            if (i < j) // 用比基准大的记录替换高位记录
                a[j--] = a[i];
        }
        System.out.println("index is " + i + " ");
        a[i] = index;// 将基准数值替换回 a[i]
        sortDemo(a, low, i - 1); // 对低子表进行递归排序
        sortDemo(a, i + 1, hight); // 对高子表进行递归排序
    }

}
